#include "tools.h"


class Solution {
public:
    ListNode* reverse(ListNode* start, ListNode* end){ // 返回首元素，因首元素 next 未修改
        ListNode *cur = start, *nxt = start->next;
        while(cur != end){
            ListNode *tmp = nxt->next;
            nxt->next = cur;
            cur = nxt;
            nxt = tmp;
        }
        return start;
    }
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode prehead(0, head);
        ListNode *pre = &prehead, *end = &prehead, *nxt;
        while(end != nullptr){ // 1 即可
            for(int i = 0; end != nullptr && i < k; ++i) end = end->next; // 先划定边界，再内部处理
            if(end == nullptr) break;

            nxt = end->next;
            ListNode* tmp = reverse(pre->next, end);
            pre->next = end;
            tmp->next = nxt;
            pre = tmp;
            end = tmp;
        }
        return prehead.next;
    }
};



int main(int argc, char const *argv[])
{
    ListNode *p = simple_list();
    show(p);

    Solution s;
    ListNode *res = s.reverseKGroup(p, 2);

    

    show(res);
    return 0;
}
